package org.zhuxian.cn.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.zhuxian.cn.filter.JwtAuthenticationFilter;

import java.util.Arrays;
import java.util.List;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    // 定义需要登录的接口列表
    private static final List<String> PROTECTED_URLS = Arrays.asList(
            "/equipment/builds/like/{id}",
            "/equipment/builds",
            "/equipment/builds/delete",
            "/equipment/builds/user/{userId}"
    );

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .cors() // 启用 CORS 支持
                .and()
                .authorizeRequests()
                // 允许 /user/login 接口匿名访问
                .antMatchers("/user/login").permitAll();

        // 对需要登录的接口进行认证配置
        for (String url : PROTECTED_URLS) {
            http.authorizeRequests().antMatchers(url).authenticated();
        }

        // 其余接口允许匿名访问
        http.authorizeRequests().anyRequest().permitAll()
                .and()
                .addFilterBefore(new JwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}